/**
 * axios全局配置，包括验证签名及错误处理
 */

import axios from 'axios'
import store from '../store'
import qs from 'qs'
import { sign } from '../utils/sign'
import { Message } from 'element-ui'

// 超时设置
const service = axios.create({
  timeout: 60000 // 请求超时时间 60s
})

// http request 拦截器
// 每次请求都未http请求头增加token, 并生成sign
service.interceptors.request.use(
  config => {
    const token = store.state.token
    if (token) {
      config.data.token = token
    }
    config.data = qs.parse(config.data)
    // 定义生成签名后的data
    let data = sign(config.data)
    // 判断请求是否为get方式并格式化参数设置
    if (config.method === 'get') {
      config.url += '?' + qs.stringify(data)
      window.location.href = config.url
    } else {
      config.data = JSON.stringify(data)
    }
    config.headers = {
      'Content-Type': 'application/x-www/form/urlencoded;charset=utf-8'
      // 'Content-Type': 'application/json;charset=utf-8'
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
// 针对响应代码确认跳转到对应页面
service.interceptors.response.use(
  response => {
    if (response.data.responseCode === '0000') {
      return response.data
    } else if (response.data.responseCode === '1002') {
      Message.error({
        message: response.data.responseCode + response.data.responseMsg,
        duration: store.state.duration
      })
    } else if (response.data.responseCode === '1004') {
      Message.error({
        message: response.data.responseCode + response.data.responseMsg + ',即将跳转至登陆页...',
        duration: store.state.duration,
        onClose: () => {
          store.commit('setToken', '')
          window.location.reload()
        }
      })
    } else if (response.data.responseCode === '1008') {
      Message.error({
        message: response.data.responseCode + response.data.responseMsg + ',即将跳转至登陆页...',
        duration: store.state.duration,
        onClose: () => {
          store.commit('setToken', '')
          window.location.reload()
        }
      })
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
